package test4_16.demo02;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class TCPClientDoubleTest {
    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        try {
            Socket socket = new Socket("localhost", 8888);
            System.out.println("客户端与服务器连接成功");

            //获取服务器数据，转成字符输出流,并封装成缓冲流
            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            //获取客服端数据
            PrintWriter pw = new PrintWriter(socket.getOutputStream());
            System.out.println("开始聊天");

            new Thread(() -> {
                String line;
                try {
                    while ((line = br.readLine()) != null) {
                        System.out.println("服务器说：" + line);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();

            new Thread(() -> {
                while (true) {
                    String message = scanner.nextLine();
                    pw.println(message);
                    pw.flush();
                }
            }).start();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
